<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

/**
 * Output class
 */
class Output {
	private static $_instance = null;
	protected $_header = array();
	protected $_body = array();

	public static function &instance() {
		if (!isset(self::$_instance)) {
			$c = __CLASS__;
			self::$_instance = new $c;
		}

		return self::$_instance;
	}

	private function __construct() {}

	public function __clone() {
		throw new Node_Exception('Can`t clone singletone object');
	}

	public static function body($cont) {
		self::instance()->_body[] = $cont;
    }

	public static function header($cont) {
		self::instance()->_header[] = $cont;
	}

	/**
	 * Send headers
	 */
	public static function sendHeaders() {
		$output = self::instance();
		foreach ($output->_header as $header) {
			header($header);
		}
	}

	/**
	 * Rendering body
	 */
	public static function renderBody() {
		$output = self::instance();

		$body = '';
		foreach ($output->_body as $body_item) {
			$body .= strval($body_item);
		}

		// Cache output body if needed
		if (Config::get('perform_output_caching', 'cache', false)) {
			$cache_key = Router::getUniqueKey();
			Cache::set($cache_key, $body, Config::get('output_ttl', 'cache', 86400));
		}

		echo $body;
	}
}
